package org.example.springbook.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.example.springbook.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    //这里运用jdk中的字符串转化
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //对那些请求处理，true的请求进行处理，false的请求不处理
        return true;
    }

    @SneakyThrows
    //对于异常加的注解
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //1.首先对字符串进行处理
        //2.然后还有对于一些包装的类型，直接返回就行了
        //3.对于其他类型的再进行包装处理
        if(body instanceof String) {
           return objectMapper.writeValueAsString(Result.success(body));
        }
        //不用再进行套用两层了
        if(body instanceof Result) {
            return body;
        }
        //对于为什么要将字符串再进行包装的时候
        //无论控制层不管返回的是true还是false
        //在经过这个统一返回的时候，code=2000，所以在前端的时候不应该只是判断code的值来判断数据是否返回成功
        //所以在控制层进行包装过后，还要判断body是否为Result类型的
        return Result.success(body);
    }
}
